package com.product.system.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.alibaba.excel.EasyExcel;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


import com.product.system.domain.LoginName;
import com.product.system.domain.User;
import com.product.system.domain.UserBarChart;
import com.product.system.service.SysPostService;
import com.product.system.service.UserPostService;
import com.product.system.service.UserService;
import com.product.system.utils.Result;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("user")
public class UserController {

    /**
     * 测试
     */
    private String name;
    @Autowired
    UserService userService;


    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    SysPostService sysPostService;

    @Value("${spring.mail.username}")
    private String setFromUserName;
//
//    @Autowired
//   private MinioClient minioClient;

//    @RequestMapping("barChart")//柱状图
//    private Result barChart(){
//       List<UserBarChart> list= userService.barChartList();
//        return Result.success(list);
//    }

//    @Autowired
//    UploadService uploadService;

//    @Autowired
//    UserPostService userPostService;
//
//    public static final String bucketName = "test";
//    public static final String accessKey = "mzFfrfXXtp6DZQw02Z4m";
//    public static final String secretKey =  "BQYa0SDyv8nE1hFtX0GMqyr4FSbOOpCOGQwraoDu";
    /**
     * 岗位下拉框
     * @return
     */
//    @RequestMapping("postList")
//    public Result postList(){
//        List<PostList> list= sysPostService.postList();
//        return Result.success(list);
//    }

    /**
     * 上传图片
     * @param
     * @return
     * @throws
     */
//  @PostMapping("addFile")
//    public Map<String,Object> addFile(MultipartFile file) throws IOException {
//       String fileName= UUID.randomUUID()+"_"+file.getOriginalFilename();
//        Map<String, Object> hashMap = new HashMap<>();
//        try {
//            minioClient.putObject(PutObjectArgs
//                    .builder()
//                    .object(fileName)//不能为空
//                    .bucket("test")
//                    .stream(file.getInputStream(),file.getSize(),-1)
//                    .contentType(file.getContentType())
//                    .build());
//            hashMap.put("code",1001);
//            hashMap.put("url","http://localhost:9000/test/"+fileName);
//        }catch (Exception e){
//            e.printStackTrace();
//            hashMap.put("code",1002);
//        }
//        return hashMap;
//    }



/*    @RequestMapping("uploadFile")
    public String uploadFile(MultipartFile file) throws Exception {
        MinioClient minioClient = MinioClient
                .builder()
                .endpoint("http://127.0.0.1:9000")
                .credentials(accessKey, secretKey)
                .build();
        String filename = UUID.randomUUID() + file.getOriginalFilename();
        try {
            minioClient.putObject(PutObjectArgs.builder().object(filename)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType()).bucket(bucketName)
                    .build());
        } catch (Exception e) {
            throw new Exception(e);
        }
        return "http://127.0.0.1:9000/" + bucketName + "/" + filename;
    }

 */






    //删除
    @RequestMapping("byUserId")
    public Result byUserId(Integer id){
       int a= userService.byUserId(id);
       if(a>0){
           return Result.success("删除成功");
       }else {
           return Result.fail("删除失败");
       }
    }


//    @XxlJob("CheckBirthDate")
//    @GetMapping("aaaaaa")
//    public void checkBirthDate() {
//       List<User> list =  userService.getList();
//        String nowDate = new SimpleDateFormat("MM-dd").format(new Date());
//
//        for (User user : list) {
//            Date birthDate = user.getBirthDate();
//            String userBirth = new SimpleDateFormat("MM-dd").format(birthDate);
//            if (nowDate.equals(userBirth)) {
//                SimpleMailMessage mailMessage = new SimpleMailMessage();
//                mailMessage.setFrom(setFromUserName);
//                //邮件主题
//                mailMessage.setSubject("生日快乐！");
//                //邮件内容：普通文件无法解析html标签
//                mailMessage.setText("<h1>好好在家待着.....</h1>");
//                //收件人
//                mailMessage.setTo(user.getEmail());
//                //发送邮件
//                javaMailSender.send(mailMessage);
//
//            }
//        }
//    }

//    @GetMapping("aaaaaa")
    @XxlJob("CheckBirthDate")
    public void checkBirthDate() {
        List<User> list =  userService.getList();
        String nowDate = new SimpleDateFormat("MM-dd").format(new Date());

        list.parallelStream().forEach(item -> {
//        list.forEach(item -> {
            Date birthDate = item.getBirthDate();
            if (birthDate!= null) {
                String userBirth = new SimpleDateFormat("MM-dd").format(birthDate);
                if (nowDate.equals(userBirth)) {
//                    SimpleMailMessage mailMessage = new SimpleMailMessage();
//                    MimeMessage mimeMessage = new MimeMessage()
//
//                    mailMessage.setFrom(setFromUserName);
//                    //邮件主题
//                    mailMessage.setSubject("生日快乐！");
//                    //邮件内容：普通文件无法解析html标签
//                    mailMessage.setText("<h1>好好在家待着.....</h1>");
//                    //收件人
//                    mailMessage.setTo(item.getEmail());
//                    //发送邮件
//                    javaMailSender.send(mailMessage);
                    //创建复杂邮件对象
                    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                    //发送复杂邮件的工具类
                    //true - 能够添加附件
                    MimeMessageHelper  helper = null;
                    try {
                        helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
                        helper.setFrom(setFromUserName);
                        helper.setSubject("生日快乐！");
                        //true - 能够再内容中编写html标签 - 会解析
                        helper.setText("<!DOCTYPE html>\n" +
                                "<html lang=\"en\">\n" +
                                "\n" +
                                "<head>\n" +
                                "    <meta charset=\"UTF-8\">\n" +
                                "    <title>"+item.getNickName()+"生日快乐!</title>\n" +
                                "</head>\n" +
                                "\n" +
                                "<body>\n" +
                                "    <div style=\"text-align: center;\">\n" +
                                "        <h1>生日快乐！</h1>\n" +
                                "        <img src=\"https://img2.baidu.com/it/u=3143797682,3987116198&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281\" alt=\"生日蛋糕\" width=\"300\">\n" +
                                "        <p>愿你的生活充满阳光和喜悦！</p>\n" +
                                "    </div>\n" +
                                "    <audio controls autoplay loop>\n" +
                                "        <audio controls autoplay loop>\n" +
                                "    <source src=\"https://fm.afbcs.cn/xbjmHC\" type=\"audio/mpeg\">\n" +
                                "    Your browser does not support the audio element.\n" +
                                "</audio>\n" +
                                "        Your browser does not support the audio element.\n" +
                                "    </audio>\n" +
                                "</body>\n" +
                                "\n" +
                                "</html>",true);
                        //添加附件
                        helper.addAttachment("aaa.jpg",new File("D:\\image\\aaa.jpg"));
                        helper.addAttachment("bbb.jpg",new File("D:\\image\\bbb.jpg"));
                        //收件人
                        helper.setTo(item.getEmail());
                        javaMailSender.send(mimeMessage);
                    } catch (MessagingException e) {
                        throw new RuntimeException(e);
                    }

                }
            }
        });
    }


    //导入Excel
    @GetMapping("getExcel")//PutMapping---GetMapping
    public void getExcel(HttpServletResponse response) throws IOException {
        //查询所有数据
        List<User> list= userService.getExcelUser();
        String fileName= URLEncoder.encode("用户信息","UTF-8").replaceAll("\\+","%20");
        //设置响应编码
        response.setCharacterEncoding("UTF-8");
        //设置响应的类型:xlsx 后缀的文件 可以参考Tomcat/conf/web.xml去找类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //设置响应头:以下载的形式 下载文件 文件名称为fileName 文件内容是什么
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //文件内容是:response.getOutputStream()
        EasyExcel.write(response.getOutputStream(), User.class).sheet("用户信息").doWrite(list);
    }

    //登录
    @RequestMapping("loginName")
    public Result loginOrName(@RequestBody LoginName loginName){
        User userAll= userService.loginOrName(loginName);
        if(userAll==null){
            return Result.fail("用户名或者密码错误");
        }

        String token = JWT.create()
                .setPayload("user", userAll)
                .setSigner(JWTSignerUtil.none())
                .sign();

        return Result.success(token);
    }

    //列表
//    @RequestMapping("loginList")
//    public Result loginList(@RequestBody User user,Integer pageNum){//@RequestBody Condition condition,
//        PageHelper.startPage(pageNum,5);
////        String[] dateAll = user.getDateAll();
////
////        if(dateAll.length>0 && dateAll!=null){
////            user.setIndate(dateAll[0]);
////            user.setOutdate(dateAll[1]);
////        }
//       List<User> userList= userService.listUser(user);
//        PageInfo<User> userPageInfo = new PageInfo<>(userList);
//        return Result.success(userPageInfo);
//    }
//    @RequestMapping("loginList")
//    public Result loginList(@RequestBody User user,Integer pageNum){//@RequestBody Condition condition,
//
//        PageHelper.startPage(pageNum,5);
//       List<User> userList= userService.listUser(user);
//        PageInfo<User> userPageInfo = new PageInfo<>(userList);
//        return Result.success(userPageInfo);
//    }

    /**
     * 测试列表
     * @return
     */
    @RequestMapping("list")
    public Result list(Integer pageNum){
        PageHelper.startPage(pageNum,5);
        List<User> userList=userService.listAll();
        PageInfo<User> userPageInfo = new PageInfo<>(userList);
        return Result.success(userPageInfo);
    }

    //添加
//    @RequestMapping("setSave")
//    public Result setSave(@RequestBody User user){
//        user.setCreateTime(new Date());
//         userService.addUser(user);
//        userPostService.addUserPost(user);
//         return Result.success();
//    }

    //修改
    @RequestMapping("updateSet")
    public Result updateSet(@RequestBody User user){
        user.setUpdateTime(new Date());
         userService.updateUser(user);
       // userPostService.updateUserPost(user);
         return Result.success();
    }

}
